<template>
  <div class="app-container">
    <div>
      <el-button type="primary" plain @click="showVacationApplyDialog">请假申请</el-button>
    </div>
    <div style="padding: 10px" />
    <el-table
      v-loading="listLoading"
      :data="list"
      style="width: 100%"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column label="状态" align="center" width="100px">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.sta==0 && scope.row.chexiao==0" type="warning">审核</el-tag>
          <el-tag v-if="scope.row.sta==1 && scope.row.chexiao==0" type="success">通过</el-tag>
          <el-tag v-if="scope.row.sta==2 && scope.row.chexiao==0" type="danger">拒绝</el-tag>
          <el-tag v-if="scope.row.chexiao==1" type="info">撤销</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="申请编号" align="center" width="100px">
        <template slot-scope="scope">
          <el-tag> {{ scope.row.id }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="申请时间" align="center" width="110px">
        <template slot-scope="scope">
          {{ getFormatedTimeStr(scope.row.createTime) }}
        </template>
      </el-table-column>

      <el-table-column label="请假类型" align="center" width="110px">
        <template slot-scope="scope">
          <b>{{ scope.row.leixing }}</b>
        </template>
      </el-table-column>

      <el-table-column label="开始时间" align="center">
        <template slot-scope="scope">
          {{ getFormatedTimeStr(scope.row.startDate) }}
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center">
        <template slot-scope="scope">
          {{ getFormatedTimeStr(scope.row.endDate) }}
        </template>
      </el-table-column>
      <el-table-column label="请假时长" align="center">
        <template slot-scope="scope">
          {{ scope.row.leixing == "因公外出" ? scope.row.days + '小时': Math.ceil(scope.row.days / 8) + '天' }}
        </template>
      </el-table-column>

      <el-table-column label="请假理由" align="center">
        <template slot-scope="scope">
          {{ scope.row.reason }}
        </template>
      </el-table-column>

      <el-table-column label="是否离开盐城" align="center">
        <template slot-scope="scope">
          {{ scope.row.outYancheng }}
        </template>
      </el-table-column>

      <el-table-column label="证明文件" align="center">
        <template slot-scope="scope">
          <el-image style="width: 48px; height: 48px" :src=" scope.row.pics[0]" :preview-src-list=" scope.row.pics" />
        </template>
      </el-table-column>

      <el-table-column label="操作" width="250px">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" plain @click="seeDetail(scope.row.id, scope.row)">详情 </el-button>
          <el-button v-if="scope.row.sta>0 && scope.row.chexiao == 0" size="mini" type="primary" plain @click="printPdf(scope.row.id)">生成PDF
          </el-button>
          <el-button v-if="(scope.row.chexiao == 0)" size="mini" type="danger" plain @click="revertApply(scope.$index)">
            撤回 </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="padding: 10px" />
    <el-pagination
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageCount"
      layout="total, sizes, prev, pager, next, jumper"
      :total="dataTotal"
      @size-change="onPageSizeChange"
      @current-change="onCurrentPageChange"
    />

    <el-dialog
      :visible.sync="vacationApplyDialog.visible"
      width="50%"
      :close-on-click-modal="false"
      top="5vh"
      center
      :show-close="false"
    >
      <div>
        <el-form ref="form" size="mini" label-position="left" label-width="100px">
          <el-row>
            <!-- 左侧 -->
            <el-col :span="11">
              <div class="title"><i class="el-icon-document" /> 申请单</div>

              <el-form-item label="申请人">
                {{ userInfo.name }}
              </el-form-item>

              <el-form-item label="请假类型">
                <el-select v-model="vacationApplyDialog.leixing" placeholder="请选择" style="width: 100%;">
                  <el-option v-for="(item,idx) in jiabieList" :key="idx" :label="item" :value="item" />
                </el-select>
              </el-form-item>

              <!-- <el-form-item label="开始时间">
                <el-date-picker
                  v-model="vacationApplyDialog.startDate"
                  type="datetime"
                  placeholder="选择日期"
                  style="width: 100%;"
                  :clearable="false"
                  @change="dateChange"
                />
              </el-form-item>

              <el-form-item label="结束时间">
                <el-date-picker
                  v-model="vacationApplyDialog.endDate"
                  type="datetime"
                  placeholder="选择日期"
                  :clearable="false"
                  style="width: 100%;"
                  @change="dateChange"
                />
              </el-form-item> -->
              <el-form-item label="选择时间">
                <el-date-picker
                style="width: 100%;"
                  v-model="value1"
                  type="datetimerange"
                  :clearable="false"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  :picker-options="pickerOptions"
                  @change="dateChange">
              </el-date-picker>
              </el-form-item>

              <el-form-item label="请假时长">
                <div style="color:red;font-weight:bold;">{{ qingjiaDaysStr() }}</div>
              </el-form-item>

              <el-form-item label="是否出盐城">
                <el-radio-group v-model="vacationApplyDialog.outYancheng" size="small" @change="yanchengChange" text-color="#fff" fill="#0b847b">
                  <el-radio-button label="否">否</el-radio-button>
                  <el-radio-button label="是">是</el-radio-button>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="请假事由">
                <el-input v-model="vacationApplyDialog.reason" type="textarea" :rows="4" placeholder="请输入内容" />
              </el-form-item>

              <el-form-item label="图片证明" label-position="top">
                <el-upload ref="uploadpic" multiple :action="uploadconfig.url" :before-upload="beforePicUpload" list-type="text">
                  <el-button size="mini" type="primary">点击上传图片</el-button>
                </el-upload>
              </el-form-item>

              <el-form-item label="附件">
                <el-upload ref="attaches" :action="uploadconfig.url" :on-success="uploadAttachSuccess" list-type="text">
                  <el-button size="mini" type="primary" plain>点击上传附件</el-button>
                </el-upload>
              </el-form-item>

            </el-col>

            <!-- 右侧 -->
            <el-col :span="11" :offset="2">
              <div class="title"><i class="el-icon-s-check" /> 审核流程</div>
              <div v-for="(item, index) in vacationApplyDialog.auditors" :key="index">
                <!-- 箭头：第一个不显示 -->
                <div v-if="index>0" class="step-arrow">
                  <el-row>
                    <el-col :span="8">
                      <div><i class="el-icon-caret-bottom" /></div>
                    </el-col>
                  </el-row>
                </div>
                <!-- 步骤样式 -->
                <div class="step">
                  <el-row>
                    <el-col :span="8">
                      <div class="step-info-left">{{ item.stepName || item.positionName }}</div>
                    </el-col>
                    <el-col :span="16">
                      <div class="step-info-right">{{ item.name }}</div>
                    </el-col>
                  </el-row>
                </div>
              </div>
            </el-col>

          </el-row>

        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="vacationApplyDialog.visible = false">关 闭</el-button>
        <el-button type="primary" @click="clickApply()">提 交</el-button>
      </span>
    </el-dialog>

    <el-dialog title="" width="60%" :visible.sync="detailDialog.visible" top="5vh">
      <qingjia-detail :id="detailDialog.id" />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="(detailDialog.visible = false)">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  websock
} from '@/websock'
import moment from 'moment'
import {
  uploadconfig
} from '@/const'
import {
  quchongAuditors
} from '@/utils/utils'
import QingjiaDetail from '../../components/details/qingjiaDetail.vue'

import { Message } from 'element-ui'

export default {
  components: {
    QingjiaDetail
  },
  filters: {
    statusFilter(sta) {
      const statusMap = {
        1: 'info',
        2: 'success',
        3: 'danger'
      }
      return statusMap[sta]
    }
  },
  data() {
    return {
      pickerOptions: {
        disabledDate(v) {
          return v.getTime() < new Date().getTime() - 86400000;//  - 86400000是否包括当天
        }
      },
      value1:[],
      uploadconfig,
      // 人员列表样式(多选)
      props: {
        multiple: true
      },
      // 人员列表数据
      userList: [],
      list: null,
      listLoading: true,
      pageIndex: 1,
      pageCount: 10,
      dataTotal: 0,
      jiabieList: [],
      auditors: [], // 审核人
      lingdao: {}, // 领导
      userInfo: {},
      qingjiaDetail: [], // 请假详情
      vacationApplyDialog: {
        visible: false,
        leixing: '事假',
        startDate: '',
        endDate: '',
        days: 0,
        outYancheng: '否',
        reason: '',
        auditors: [],
        attaches: [],
        pics: []
      },
      detailDialog: {
        visible: false,
        id: 0
      }
    }
  },
  async created() {
    this.getList()

    websock.qingjiaList().then(data => {
      this.jiabieList = []
      for (let i = 0; i != data.length; i++) {
        this.jiabieList.push(data[i].name)
      }
    })

    this.userInfo = await websock.getUserInfo()

    const res = await websock.getContactList()
    console.log('created', res)
    const userList = []
    for (let i = 0; i !== res.length; i++) {
      userList.push({
        value: i + '',
        label: res[i].name,
        children: []
      })
      for (let j = 0; j !== res[i].userList.length; j++) {
        userList[i].children.push({
          value: res[i].userList[j].uid,
          label: res[i].userList[j].name
        })
      }
    }

    this.userList = userList

    this.auditors = await websock.getAuditors({
      typ: 0
    })
    console.log('auditors', this.auditors)
    quchongAuditors(this.auditors)
    this.vacationApplyDialog.auditors = this.auditors.slice()

    this.lingdao = await websock.getLingdao()
    console.log('my lingdao info', this.lingdao)
  },
  methods: {
    // 获取当前年月日时分秒
    getTime() {
      function addZero(num) {
					return num < 10 ? '0' + num : num;
				}
      // 创建一个 Date 对象
      const now = new Date();
      // 获取当前年份
      const year = now.getFullYear();
      // 获取当前月份（注意：月份从 0 开始计数）
      const month = addZero(now.getMonth() + 1);
      // 获取当前日期
      const date = addZero(now.getDate());

      // 输出结果
      this.value1 = [`${year}-${month}-${date} 09:00:00`,`${year}-${month}-${date} 17:00:00`];
      // this.vacationApplyDialog.startDate = this.value1[0];
      // this.vacationApplyDialog.endDate = this.value1[1];
      this.dateChange();
    },

    // 获取格式化时间字符串
    getFormatedTimeStr(stamp, str = 'MM-DD HH:mm') {
      return moment(stamp).format(str)
    },
    getList() {
      this.listLoading = true
      websock.vacationApplyRecordWeb({
        pageIndex: this.pageIndex,
        pageCount: this.pageCount
      }).then(
        (data) => {
          this.listLoading = false
          this.list = data.list
          this.dataTotal = data.count
        }
      )
    },
    onPageSizeChange(val) {
      this.pageCount = val
      this.getList()
    },
    onCurrentPageChange(val) {
      this.pageIndex = val
      this.getList()
    },
    async dateChange() {
      // 判断选择的时间  --- 开始
      let startDate = this.value1[0];
      let endDate = this.value1[1];
      // 判断是否选择时分秒
      const lastSixStartDate = startDate.substr(-8);
      const lastSixEndDate = endDate.substr(-8);

      // 没有选择时分秒，默认变成9和17
      if(lastSixStartDate==='00:00:00') {
        this.vacationApplyDialog.startDate = this.value1[0].substr(0, 10)+' 09:00:00';
        this.value1[0] = this.vacationApplyDialog.startDate;
      } else {
        this.vacationApplyDialog.startDate = this.value1[0];
      }

      if(lastSixEndDate==='00:00:00') {
        this.vacationApplyDialog.endDate = this.value1[1].substr(0, 10)+' 17:00:00';
        this.value1[1] = this.vacationApplyDialog.endDate;
      } else {
        this.vacationApplyDialog.endDate = this.value1[1];
      }
      // 判断选择的时间  --- 结束
      console.log(this.vacationApplyDialog.startDate,this.vacationApplyDialog.endDate,'value1value1')

      // this.vacationApplyDialog.startDate = this.value1[0];
      // this.vacationApplyDialog.endDate = this.value1[1];

      console.log('date change', this.vacationApplyDialog)
      if (this.vacationApplyDialog.startDate && this.vacationApplyDialog.endDate) {
        let startTime = moment(this.vacationApplyDialog.startDate).format('YYYY-MM-DD HH:mm:ss')
        let endTime = moment(this.vacationApplyDialog.endDate).format('YYYY-MM-DD HH:mm:ss')
        if (this.vacationApplyDialog.leixing != '因公外出') {
          startTime = moment(startTime).startOf('day').format('YYYY-MM-DD HH:mm:ss')
          endTime = moment(endTime).endOf('day').format('YYYY-MM-DD HH:mm:ss')
        }

        this.qingjiaDetail = await websock.getShangbanDetail({ startTime, endTime })
        console.log('qingjia detail', this.qingjiaDetail)
      }

      this.checkAuditors()
    },
    uploadAttachSuccess(res, file) {
      console.log('upload attach success', res, file)
      if (res.code !== 0) {
        return Message({
          message: res.message || 'error',
          type: 'error',
          duration: 3 * 1000
        })
      }
      this.vacationApplyDialog.attaches.push({
        name: file.name,
        path: res.data
      })
    },
    yanchengChange() {
      this.checkAuditors()
    },
    addAuditor(info) {
      console.log('add auditor', info)
      if (!info.uid) return
      for (let i = 0; i != this.vacationApplyDialog.auditors.length; i++) {
        if (this.vacationApplyDialog.auditors[i].uid == info.uid) return
      }

      this.vacationApplyDialog.auditors.push(info)
    },
    checkAuditors() {
      // 塞一个默认审核人
      this.vacationApplyDialog.auditors = []
      const defaultAuditors = this.auditors.slice()
      console.log('default auditors', defaultAuditors)
      for (let i = 0; i != defaultAuditors.length; i++) {
        if (defaultAuditors[i].sta == '0') {
          this.vacationApplyDialog.auditors.push(defaultAuditors[i])
        }
      }
      // 请假小时数
      let hours = 0
      let diff = 0
      for (let i = 0; i != this.qingjiaDetail.length; i++) {
        const detail = this.qingjiaDetail[i]
        if (moment(detail.start).isAfter(moment(detail.end))) continue
        diff += (moment(detail.end).valueOf() - moment(detail.start).valueOf())
      }

      console.log(diff)
      hours = Math.ceil(diff / 1000 / 60 / 60)

      // 是否为科长
      const isKezhang = this.userInfo.uid == this.lingdao.zhijie_lingdao
      // 是否出盐城
      const outYancheng = this.vacationApplyDialog.outYancheng == '是'
      if (hours > 8 || isKezhang) {
        console.log('add fenguan lingdao')
        this.addAuditor({
          uid: this.lingdao.fenguan_lingdao,
          name: this.lingdao.fenguan_lingdao_name,
          positionName: this.lingdao.fenguan_lingdao_position_name
        })
      }

      console.log('check auditors final', this.vacationApplyDialog.outYancheng, outYancheng, hours, isKezhang)
      if (outYancheng || hours > 8 || (hours > 0 && isKezhang)) {
        console.log('add zhuyao lingdao')
        this.addAuditor({
          uid: this.lingdao.zhuyao_lingdao,
          name: this.lingdao.zhuyao_lingdao_name,
          positionName: this.lingdao.zhuyao_lingdao_position_name
        })
      }
    },
    qingjiaDaysStr() {
      let hours = 0
      let diff = 0
      for (let i = 0; i != this.qingjiaDetail.length; i++) {
        const detail = this.qingjiaDetail[i]
        if (moment(detail.start).isAfter(moment(detail.end))) continue
        diff += (moment(detail.end).valueOf() - moment(detail.start).valueOf())
      }

      hours = Math.ceil(diff / 1000 / 60 / 60)

      if (this.vacationApplyDialog.leixing == '因公外出') {
        return hours + ' 小时'
      }

      return Math.ceil(hours / 8) + '天'
    },
    beforePicUpload(file) {
      const isPic = file.type === 'image/jpeg' || file.type === 'image/png'
      console.log('before pic upload', file.type)
      if (!isPic) this.$message.error('只能上传jpg或png格式')
      return isPic
    },
    handleRemovePic(file) {
      const fileList = this.$refs.uploadpic.uploadFiles
      console.log(fileList)
      const index = fileList.findIndex((fileItem) => {
        return fileItem.uid === file.uid
      })
      fileList.splice(index, 1)
    },
    // 显示添加员工界面
    showVacationApplyDialog() {
      this.vacationApplyDialog.visible = true
      this.vacationApplyDialog.leixing = this.jiabieList[0]
      this.vacationApplyDialog.startDate = ''
      this.vacationApplyDialog.endDate = ''
      this.vacationApplyDialog.days = 0
      this.vacationApplyDialog.outYancheng = '否'
      this.vacationApplyDialog.reason = ''
      this.vacationApplyDialog.pics = []
      this.vacationApplyDialog.attaches = []
      this.getTime();

      if (this.$refs.attaches) this.$refs.attaches.uploadFiles = []
    },
    async clickApply() {
      console.log('click apply', this.vacationApplyDialog)
      if (this.vacationApplyDialog.startDate == '') {
        return this.$message.error('请选择开始时间')
      }

      if (this.vacationApplyDialog.endDate == '') {
        return this.$message.error('请选择结束时间')
      }

      if (this.vacationApplyDialog.reason == '') {
        return this.$message.error('请输入请假原因')
      }

      // 请假开始时间不能早于今天
      if (moment(this.vacationApplyDialog.startDate).startOf('day').isBefore(moment().startOf('day'))) {
        return this.$message.error('请假开始时间不能早于今天')
      }

      // 请假小时数
      let hours = 0
      let diff = 0
      for (let i = 0; i != this.qingjiaDetail.length; i++) {
        const detail = this.qingjiaDetail[i]
        if (moment(detail.start).isAfter(moment(detail.end))) continue
        diff += (moment(detail.end).valueOf() - moment(detail.start).valueOf())
      }

      hours = Math.ceil(diff / 1000 / 60 / 60)

      if (hours <= 0) {
        return this.$message.error('请检查选择的时间')
      }

      const auditors = []
      for (let i = 0; i != this.vacationApplyDialog.auditors.length; i++) {
        auditors.push({
          uid: this.vacationApplyDialog.auditors[i].uid,
          stepName: this.vacationApplyDialog.auditors[i].stepName || this.vacationApplyDialog.auditors[i]
            .positionName
        })
      }

      const pics = []
      const fileList = this.$refs.uploadpic.uploadFiles
      for (let i = 0; i != fileList.length; i++) {
        pics.push(fileList[i].response.data)
      }

      try {
        await websock.vacationApply({
          leixing: this.vacationApplyDialog.leixing,
          startDate: moment(this.vacationApplyDialog.startDate).format('YYYY-MM-DD HH:mm:ss'),
          endDate: moment(this.vacationApplyDialog.endDate).format('YYYY-MM-DD HH:mm:ss'),
          days: hours,
          detail: this.qingjiaDetail,
          outYancheng: this.vacationApplyDialog.outYancheng,
          reason: this.vacationApplyDialog.reason,
          attaches: this.vacationApplyDialog.attaches,
          auditors,
          pics
        })

        this.$message.success('提交成功，等待审核')

        this.vacationApplyDialog.visible = false
        this.getTime();

        this.getList()
      } catch (err) {
        this.$message.error(err.message || 'error')
      }
    },
    async revertApply(idx) {
      try {
        await websock.revertVacationApply({
          id: this.list[idx].id
        })
        this.list[idx].sta = 4
        this.getList()
      } catch (err) {
        console.error(err)
        this.$message.error({
          title: err.message || 'error'
        })
      }
    },
    seeDetail(id, row) {
      this.detailDialog.visible = true
      this.detailDialog.id = id
      console.log(row)
    },
    printPdf(id) {
      websock.printPdf({
        typ: 0,
        id
      }).then(res => {
        console.log('print pdf', res)
        const a = document.createElement('a')
        a.style.display = 'none'
        a.href = res
        a.target = '_blank'
        document.body.appendChild(a)
        a.click()
        URL.revokeObjectURL(a.href)
        document.body.removeChild(a)
      })
    }
  }
}
</script>

<style>
  @import url('../../styles/form.css');
</style>
